<template>
  <div class="user-center-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1><i class="el-icon-user"></i> 个人中心</h1>
      <p>管理您的个人信息、订单和收藏</p>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 个人信息卡片 -->
      <el-card class="user-info-card">
        <div slot="header" class="card-header">
          <span>个人信息</span>
          <div class="actions">
            <el-button type="primary" size="small" @click="showEditDialog = true">编辑信息</el-button>
            <el-button type="warning" size="small" @click="showPasswordDialog = true">修改密码</el-button>
          </div>
        </div>
        
        <div class="user-details">
          <div class="avatar-container">
            <el-avatar :size="100" :src="userAvatar" class="user-avatar"></el-avatar>
            <div class="username">{{ userInfo.username }}</div>
            <div class="role">{{ userInfo.isAdmin ? '管理员' : '普通用户' }}</div>
          </div>
          
          <div class="info-container">
            <div class="info-item">
              <span class="label"><i class="el-icon-user"></i> 用户ID:</span>
              <span class="value">{{ userInfo.id }}</span>
            </div>
            <div class="info-item">
              <span class="label"><i class="el-icon-phone"></i> 手机号:</span>
              <span class="value">{{ userInfo.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label"><i class="el-icon-message"></i> 邮箱:</span>
              <span class="value">{{ userInfo.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label"><i class="el-icon-date"></i> 注册时间:</span>
              <span class="value">{{ userInfo.registerTime || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label"><i class="el-icon-circle-check"></i> 状态:</span>
              <span class="value status" :class="{'active': userInfo.status === 1}">
                {{ userInfo.status === 1 ? '正常' : '已禁用' }}
              </span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 订单管理部分 -->
      <el-tabs v-model="activeOrderTab" class="order-tabs" @tab-click="loadOrderData">
        <el-tab-pane label="房间订单" name="room">
          <el-table 
            :data="roomOrders" 
            style="width: 100%"
            v-loading="roomOrdersLoading"
          >
            <el-table-column prop="id" label="订单ID" width="100"></el-table-column>
            <!-- <el-table-column label="房间ID" width="100">
              <template slot-scope="scope">
                {{ scope.row.roomId || 'N/A' }}
              </template>
            </el-table-column> -->
            <el-table-column label="房间号"  width="100">
              <template slot-scope="scope">
                {{ formatRoomId(scope.row.roomId) }}
              </template>
            </el-table-column>
            <el-table-column label="入住日期/退房日期" width="180">
              <template slot-scope="scope">
                {{ scope.row.checkInDate }} 至 {{ scope.row.checkOutDate }}
              </template>
            </el-table-column>
            <el-table-column prop="orderTime" label="下单时间" width="120"></el-table-column>
            <el-table-column label="总价" width="120">
              <template slot-scope="scope">
                ¥{{ scope.row.totalPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="支付方式" width="100">
              <template slot-scope="scope">
                 {{ scope.row.paymentMethod || '未支付'}}
              </template>
            </el-table-column>
            <el-table-column label="支付时间" width="100">
              <template slot-scope="scope">
                 {{ scope.row.paymentTime || '未支付'}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  size="mini" 
                  @click="showItemDetail(scope.row.roomId, 'room',scope.row.id)"
                >详情</el-button>
                <el-button 
                  v-if="[1, 2].includes(scope.row.status)" 
                  type="danger" 
                  size="mini" 
                  @click="handleCancelOrderStatus('room', scope.row.id)"
                >
                  取消订单
                </el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="mini" 
                  @click="handleCancelOrder('room', scope.row.id)"
                ></el-button>
                <!-- <span v-else>不可操作</span> -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="座位订单" name="seat">
          <el-table 
            :data="seatOrders" 
            style="width: 100%"
            v-loading="seatOrdersLoading"
          >
            <el-table-column prop="id" label="订单ID" width="80"></el-table-column>
            <!-- <el-table-column label="座位ID" width="80">
              <template slot-scope="scope">
                {{ scope.row.seatId || 'N/A' }}
              </template>
            </el-table-column> -->
            <el-table-column label="座位号" width="100">
              <template slot-scope="scope">
                {{ formatSeatId(scope.row.seatId) }}
              </template>
            </el-table-column>
            <el-table-column label="订单日期/时间" width="180">
              <template slot-scope="scope">
                {{ scope.row.orderDate }} {{ scope.row.orderTime }}
              </template>
            </el-table-column>
             <el-table-column prop="createTime" label="下单时间" width="180"></el-table-column>
             <el-table-column label="总价" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.totalPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="用餐人数" width="100">
              <template slot-scope="scope">
                {{ scope.row.peopleCount }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="支付方式" width="100">
              <template slot-scope="scope">
                 {{ scope.row.paymentMethod || '未支付'}}
              </template>
            </el-table-column>
            <el-table-column label="支付时间" width="100">
              <template slot-scope="scope">
                 {{ scope.row.paymentTime || '未支付'}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  size="mini" 
                  @click="showItemDetail(scope.row.seatId, 'seat',scope.row.id)"
                >详情</el-button>
                <el-button 
                  v-if="[1, 2].includes(scope.row.status)" 
                  type="danger" 
                  size="mini" 
                  @click="handleCancelOrderStatus('seat', scope.row.id)"
                >
                  取消订单
                </el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="mini" 
                  @click="handleCancelOrder('seat', scope.row.id)"
                ></el-button>
                <!-- <span v-else>不可操作</span> -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="菜品订单" name="dish">
          <el-table 
            :data="dishOrders" 
            style="width: 100%"
            v-loading="dishOrdersLoading"
          >
            <el-table-column prop="id" label="订单ID" width="100"></el-table-column>
            <el-table-column label="关联座位订单" width="120">
              <template slot-scope="scope">
                {{ scope.row.seatOrderId || '无' }}
              </template>
            </el-table-column>
            <el-table-column prop="orderTime" label="下单时间" width="180"></el-table-column>
            <el-table-column label="总价" width="120">
              <template slot-scope="scope">
                ¥{{ scope.row.totalPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="支付方式" width="120">
              <template slot-scope="scope">
                {{ scope.row.paymentMethod || '未支付' }}
              </template>
            </el-table-column>
            <el-table-column label="支付时间" width="180">
              <template slot-scope="scope">
                {{ scope.row.paymentTime || '未支付' }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  size="mini" 
                  @click="showItemDetail(scope.row.id, 'dish',scope.row.id)"
                >详情</el-button>
                <el-button 
                  v-if="[1, 2].includes(scope.row.status)" 
                  type="danger" 
                  size="mini" 
                  @click="handleCancelOrderStatus('dish', scope.row.id)"
                >
                  取消订单
                </el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="mini" 
                  @click="handleCancelOrder('dish', scope.row.id)"
                ></el-button>
                <!-- <span v-else>不可操作</span> -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 收藏管理部分 -->
      <el-tabs v-model="activeCollectionTab" class="collection-tabs">
        <el-tab-pane label="房间收藏" name="room">
          <el-table 
            :data="filterCollections(1)" 
            style="width: 100%" 
            height="250"
            v-loading="collectionLoading"
          >
            <el-table-column prop="id" label="收藏ID" width="100"></el-table-column>
            <!-- <el-table-column prop="itemId" label="房间ID" width="100"></el-table-column> -->
             <el-table-column label="房间号" prop="itemId" width="100">
              <template slot-scope="scope">
                {{ formatRoomId(scope.row.itemId) }}
              </template>
            </el-table-column>
            <el-table-column prop="collectTime" label="收藏时间" width="180"></el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  icon="el-icon-view" 
                  size="mini" 
                  @click="showCollectionDetail(scope.row, 'room')"
                >详情</el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="mini" 
                  @click="removeCollection(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="座位收藏" name="seat">
          <el-table 
            :data="filterCollections(2)" 
            style="width: 100%" 
            height="250"
            v-loading="collectionLoading"
          >
            <el-table-column prop="id" label="收藏ID" width="100"></el-table-column>
            <!-- <el-table-column prop="itemId" label="座位ID" width="100"></el-table-column> -->
            <el-table-column label="座位号" prop="itemId" width="100">
              <template slot-scope="scope">
                {{ formatSeatId(scope.row.itemId) }}
              </template>
            </el-table-column>
            <el-table-column prop="collectTime" label="收藏时间" width="180"></el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  icon="el-icon-view" 
                  size="mini" 
                  @click="showCollectionDetail(scope.row, 'seat')"
                >详情</el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="mini" 
                  @click="removeCollection(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="菜品收藏" name="dish">
          <el-table 
            :data="filterCollections(3)" 
            style="width: 100%" 
            height="250"
            v-loading="collectionLoading"
          >
            <el-table-column prop="id" label="收藏ID" width="100"></el-table-column>
            <!-- <el-table-column prop="itemId" label="菜品ID" width="100"></el-table-column> -->
             <el-table-column label="菜品名" prop="itemId" width="100">
              <template slot-scope="scope">
                {{ formatDishId(scope.row.itemId) }}
              </template>
            </el-table-column>
            <el-table-column prop="collectTime" label="收藏时间" width="180"></el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  icon="el-icon-view" 
                  size="mini" 
                  @click="showCollectionDetail(scope.row, 'dish')"
                >详情</el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="mini" 
                  @click="removeCollection(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 编辑个人信息对话框 -->
    <el-dialog title="编辑个人信息" :visible.sync="showEditDialog" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" ></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveUserInfo">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="showPasswordDialog" width="500px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input type="password" v-model="passwordForm.oldPassword" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="passwordForm.newPassword" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="passwordForm.confirmPassword" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPasswordDialog = false">取 消</el-button>
        <el-button type="primary" @click="changepassword">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 收藏详情对话框 -->
    <el-dialog :title="detailDialogTitle" :visible.sync="showDetailDialog" width="600px">
      <div v-if="detailLoading" style="text-align: center; padding: 20px;">
        <i class="el-icon-loading"></i> 加载中...
      </div>
      <div v-else>
        <!-- 房间详情 -->
        <div v-if="detailType === 'room' && detailData">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="房间号">{{ detailData.roomNumber }}</el-descriptions-item>
            <el-descriptions-item label="类型">{{ detailData.type }}</el-descriptions-item>
            <el-descriptions-item label="价格">¥{{ detailData.price.toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="可容纳人数">{{ detailData.capacity }}人</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="detailData.status === 1 ? 'success' : (detailData.status === 0 ? 'warning' : (detailData.status === 2 ? 'info' : 'danger'))">
                {{ detailData.status === 1 ? '空闲' : (detailData.status === 0 ? '已预订' : (detailData.status === 2 ? '已入住' : '维修中')) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="描述">{{ detailData.description }}</el-descriptions-item>
            <el-descriptions-item label="图片">
              <img :src="detailData.imageUrl" style="max-width: 100%; max-height: 200px; border-radius: 4px;" />
            </el-descriptions-item>
          </el-descriptions>

          <!-- 添加房间预订表单 -->
          <el-form :model="roomReserveForm" :rules="reserveRules" label-width="100px" style="margin-top: 20px;">
            <el-form-item label="入住日期" prop="checkInDate" required>
              <el-date-picker
                v-model="roomReserveForm.checkInDate"
                type="date"
                placeholder="选择入住日期"
                :picker-options="roomCheckInOptions"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            
            <el-form-item label="退房日期" prop="checkOutDate" required>
              <el-date-picker
                v-model="roomReserveForm.checkOutDate"
                type="date"
                placeholder="选择退房日期"
                :picker-options="roomCheckOutOptions"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="入住天数">
              <div class="stay-days">
                <el-tag type="info">{{ stayDays }} 晚</el-tag>
              </div>
            </el-form-item>
            
            <el-form-item label="总价">
              <div class="total-price">¥{{ totalPrice.toFixed(2) }}</div>
            </el-form-item>
            
            <el-form-item label="支付方式" required>
              <el-select v-model="roomReserveForm.paymentMethod">
                <el-option label="支付宝" value="alipay" />
                <el-option label="微信支付" value="wechat" />
                <el-option label="银行卡" value="bankcard" />
                <el-option label="到店支付" value="cash" />
              </el-select>
            </el-form-item>
            
            
          </el-form>
        </div>
        
        <!-- 座位详情 -->
        <div v-if="detailType === 'seat' && detailData">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="座位号">{{ detailData.seatNumber }}</el-descriptions-item>
            <el-descriptions-item label="区域">{{ detailData.area }}</el-descriptions-item>
            <el-descriptions-item label="可坐人数">{{ detailData.capacity }}人</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="detailData.status === 1 ? 'success' : 'warning'">
                {{ detailData.status === 1 ? '空闲' : '已预订' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="描述">{{ detailData.description }}</el-descriptions-item>
          </el-descriptions>

           <!-- 添加座位预订表单 -->
          <el-form :model="seatReserveForm" label-width="100px" style="margin-top: 20px;">
            <el-form-item label="用餐人数" required>
              <el-input-number 
                v-model="seatReserveForm.peopleCount" 
                :min="1" 
                :max="detailData.capacity"
              />
            </el-form-item>
            
            <el-form-item label="预订日期" required>
              <el-date-picker 
                v-model="seatReserveForm.orderDate" 
                type="date" 
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            
            <el-form-item label="预订时间" required>
              <el-time-select
                v-model="seatReserveForm.orderTime"
                :picker-options="{
                  start: '08:00',
                  step: '00:30',
                  end: '22:00'
                }"
                placeholder="选择时间"
              />
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 菜品详情 -->
        <div v-if="detailType === 'dish' && detailData">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="菜品名称">{{ detailData.name }}</el-descriptions-item>
            <el-descriptions-item label="分类">{{ dishCategoryName }}</el-descriptions-item>
            <el-descriptions-item label="价格">¥{{ detailData.price.toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
                {{ detailData.status === 1 ? '上架' : '下架' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="描述">{{ detailData.description }}</el-descriptions-item>
            <el-descriptions-item label="是否推荐">
              <el-tag :type="detailData.isRecommended === 1 ? 'success' : 'info'">
                {{ detailData.isRecommended === 1 ? '是' : '否' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="图片">
              <img :src="detailData.imageUrl" style="max-width: 100%; max-height: 200px; border-radius: 4px;" />
            </el-descriptions-item>
          </el-descriptions>
          <el-form label-width="100px" style="margin-top: 20px;">
            <el-form-item label="购买数量">
              <el-input-number 
                v-model="cartQuantity" 
                :min="1" 
                :step="1"
              />
            </el-form-item>
          </el-form>
        </div>
        
      </div>
      <!-- 在收藏详情对话框的footer部分 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDetailDialog = false">关 闭</el-button>
          
          <!-- 根据收藏类型显示不同按钮 -->
          <el-button 
            v-if="detailType === 'room'" 
            type="primary" 
            @click="handleBookRoom"
            :loading="roomBookingLoading"
          >
            预订该房间
          </el-button>
          
          <el-button 
            v-if="detailType === 'seat'" 
            type="primary" 
            @click="handleBookSeat"
            :loading="seatBookingLoading"
          >
            预订该座位
          </el-button>
          
          <el-button 
            v-if="detailType === 'dish'" 
            type="primary" 
            @click="handleAddToCart"
            :loading="cartLoading"
          >
            加入购物车
          </el-button>
        </span>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog :title="ItemDetailDialogTitle" :visible.sync="ItemShowDetailDialog" width="600px">
      <div v-if="ItemDetailLoading" style="text-align: center; padding: 20px;">
        <i class="el-icon-loading"></i> 加载中...
      </div>
      <div v-else>
        <!-- 房间详情 -->
        <div v-if="ItemDetailType === 'room' && ItemDetailData">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="房间号1">{{ ItemDetailData.roomNumber }}</el-descriptions-item>
            <el-descriptions-item label="类型">{{ ItemDetailData.type }}</el-descriptions-item>
            <el-descriptions-item label="价格">¥{{ ItemDetailData.price.toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="可容纳人数">{{ ItemDetailData.capacity }}人</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="ItemDetailData.status === 1 ? 'success' : (ItemDetailData.status === 0 ? 'warning' : (ItemDetailData.status === 2 ? 'info' : 'danger'))">
                {{ ItemDetailData.status === 1 ? '空闲' : (ItemDetailData.status === 0 ? '已预订' : (ItemDetailData.status === 2 ? '已入住' : '维修中')) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="描述">{{ ItemDetailData.description }}</el-descriptions-item>
            <el-descriptions-item label="图片">
              <img :src="ItemDetailData.imageUrl" style="max-width: 100%; max-height: 200px; border-radius: 4px;" />
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 座位详情 -->
        <div v-if="ItemDetailType === 'seat' && ItemDetailData">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="座位号">{{ ItemDetailData.seatNumber }}</el-descriptions-item>
            <el-descriptions-item label="区域">{{ ItemDetailData.area }}</el-descriptions-item>
            <el-descriptions-item label="可坐人数">{{ ItemDetailData.capacity }}人</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="ItemDetailData.status === 1 ? 'success' : 'warning'">
                {{ ItemDetailData.status === 1 ? '空闲' : '已预订' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="描述">{{ ItemDetailData.description }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div v-if="ItemDetailType === 'dish' && dishOrderDetail">
        <!-- 订单基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单ID">{{ dishOrderDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(dishOrderDetail.status)" size="small">
              {{ getStatusText(dishOrderDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ dishOrderDetail.orderTime }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ dishOrderDetail.totalPrice.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ dishOrderDetail.paymentMethod || '未支付' }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ dishOrderDetail.paymentTime || '未支付' }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 订单菜品列表 -->
        <div style="margin-top: 20px;">
          <h3>菜品列表</h3>
          <el-table :data="dishOrderItems" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="id" label="订单项ID" width="100" align="center"></el-table-column>
            <el-table-column label="菜品信息" width="300">
              <template slot-scope="scope">
                <div v-if="scope.row.dishInfo" style="display: flex; align-items: center;">
                  <el-image 
                    :src="scope.row.dishInfo.imageUrl" 
                    style="width: 60px; height: 60px; border-radius: 4px; margin-right: 10px;"
                    fit="cover"
                  ></el-image>
                  <div>
                    <div style="font-weight: bold;">{{ scope.row.dishInfo.name }}</div>
                    <div style="color: #909399; font-size: 12px;">
                      {{ dishCategories[scope.row.dishInfo.categoryId] || '未知分类' }}
                    </div>
                  </div>
                </div>
                <div v-else style="color: #f56c6c;">菜品信息加载失败</div>
              </template>
            </el-table-column>
            <el-table-column label="单价" width="100" align="center">
              <template slot-scope="scope">
                ¥{{ scope.row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" align="center"></el-table-column>
            <el-table-column label="小计" width="120" align="center">
              <template slot-scope="scope">
                ¥{{ scope.row.subtotal.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 订单总计 -->
          <div style="text-align: right; margin-top: 20px; font-size: 16px;">
            <span style="margin-right: 20px;">菜品数量: {{ dishOrderItems.length }} 项</span>
            <span style="font-weight: bold;">订单总计: ¥{{ dishOrderDetail.totalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </div>
        
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="ItemShowDetailDialog = false">取 消</el-button>
        <el-button 
        v-if="dishOrderDetail && dishOrderDetail.status === 1" 
        type="primary" 
        @click="handlePayOrder(dishOrderDetail.id,'dish')"
      >
        支付订单
      </el-button>
      <el-button 
       v-if="ItemDetailType === 'seat' && ItemDetailData.status === 1"
        type="primary" 
        @click="handlePayOrder( currentSeatId,'seat')"
      >
        支付订单
      </el-button>
      <el-button 
       v-if="ItemDetailType === 'room' && ItemDetailData.status === 1"
        type="primary" 
        @click="handlePayOrder( currentRoomId,'room')"
      >
        支付订单
      </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken, getUserId } from '@/utils/auth.js';
import { addRoomorder, getRoomorderByUserId, delRoomorder,listRoomorder ,updateRoomorder ,updateRoomorderStatusById} from '@/api/Roomorder.js';
import { addSeatorder, getSeatorderByUserId, delSeatorder ,listSeatorder,updateSeatorder ,updateSeatorderStatusById} from '@/api/Seatorder.js';
import { getDishorderByUserId, delDishorder ,updateDishorder,getDishorder ,updateDishorderStatusById } from '@/api/Dishorder.js';
import { getRoom ,listRoom} from '@/api/Room.js';
import { getSeat, listSeat} from '@/api/Seat.js';
import { getDish, listDish } from '@/api/Dish.js';
import { getDishcategory ,listDishcategory  } from '@/api/Dishcategory.js';
import { getCollectionByUserId, delCollectionInfo } from '@/api/Collection.js';
import { getUser, updateUser,ChangePassword } from '@/api/User.js';
import { addDishcart } from '@/api/Dishcart.js'
import MapUtils from '@/utils/mapUtils';

export default {
  name: 'UserCenter',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    // 入住日期验证规则
    const validateCheckInDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择入住日期'));
      } else {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const selectedDate = new Date(value);
        
        if (selectedDate < today) {
          callback(new Error('入住日期不能早于今天'));
        } else {
          callback();
        }
      }
    };

    // 退房日期验证规则
    const validateCheckOutDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择退房日期'));
      } else if (!this.reserveForm.checkInDate) {
        callback(new Error('请先选择入住日期'));
      } else {
        const checkInDate = new Date(this.reserveForm.checkInDate);
        const checkOutDate = new Date(value);
        
        if (checkOutDate <= checkInDate) {
          callback(new Error('退房日期必须晚于入住日期'));
        } else {
          callback();
        }
      }
    };
    
    return {
      //当前的房间订单id,或者座位订单id
      currentRoomId:0,
      currentSeatId:0,
        // 新增数据
      dishCategories: [], // 存储菜品分类映射
      dishOrderDetail: null, // 存储菜品订单详情
      dishOrderItems: [], // 存储订单菜品项
      // 新增：存储现有订单数据
      existingOrders: [],
       existingSeats: [],
       // 新增数据属性
    roomBookingLoading: false,
    seatBookingLoading: false,
    cartLoading: false,
    
    // 房间预订表单
    roomReserveForm: {
      checkInDate: '',
      checkOutDate: '',
      paymentMethod: 'alipay'
    },
    
    // 座位预订表单
    seatReserveForm: {
      peopleCount: 1,
      orderDate: '',
      orderTime: ''
    },
    
    // 购物车数量
    cartQuantity: 1,
       // 收藏详情相关数据
      showDetailDialog: false,
      detailType: '', // 'room', 'seat', 'dish'
      detailData: null,
      detailLoading: false,
      dishCategoryName: '',
      detailDialogTitle: '收藏详情',
      // 订单详情相关数据
      ItemShowDetailDialog: false,
      ItemDetailType: '', // 'room', 'seat'
      ItemDetailData: null,
      ItemDetailLoading: false,
      ItemDishCategoryName: '',
      ItemDetailDialogTitle: '订单详情',
      // 用户信息
      userInfo: {
        id: 0,
        username: '',
        phone: '',
        email: '',
        registerTime: '',
        status: 0,
        isAdmin: 0
      },
      // 订单数据
      roomOrders: [],
      seatOrders: [],
      dishOrders: [],
      // 加载状态
      roomOrdersLoading: false,
      seatOrdersLoading: false,
      dishOrdersLoading: false,
      collectionLoading: false,
      // 收藏数据
      collections: [],
      // 活动标签
      activeOrderTab: 'room',
      activeCollectionTab: 'room',
      // 对话框控制
      showEditDialog: false,
      showPasswordDialog: false,
      // 表单数据
      editForm: {
        username: '',
        phone: '',
        email: ''
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      roomCheckInOptions: {
        disabledDate: time => {
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          return time.getTime() < today.getTime();
        }
      },
      
      roomCheckOutOptions: {
        disabledDate: time => {
          if (!this.roomReserveForm.checkInDate) return true;
          const checkInDate = new Date(this.roomReserveForm.checkInDate);
          checkInDate.setHours(0, 0, 0, 0);
          return time.getTime() <= checkInDate.getTime();
        }
      },
      reserveRules: {
        checkInDate: [
          { required: true, validator: validateCheckInDate, trigger: 'change' }
        ],
        checkOutDate: [
          { required: true, validator: validateCheckOutDate, trigger: 'change' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ]
      },
      
      // 密码规则
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    // 计算入住天数
    stayDays() {
      if (this.roomReserveForm.checkInDate && this.roomReserveForm.checkOutDate) {
        const start = new Date(this.roomReserveForm.checkInDate);
        const end = new Date(this.roomReserveForm.checkOutDate);
        const diffTime = Math.abs(end - start);
        return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      }
      return 0;
    },
    
    // 计算总价
    totalPrice() {
      if (this.detailData && this.detailData.price) {
        return this.stayDays * this.detailData.price;
      }
      return 0;
    },
    userAvatar() {
      // 根据用户名生成头像
      const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
      const colorIndex = this.userInfo.id % colors.length;
      return `https://dummyimage.com/100x100/${colors[colorIndex].substring(1)}/ffffff&text=${this.userInfo.username.charAt(0)}`;
    }
  },
  created() {
    // 检查登录状态
    if (!getToken()) {
      this.$router.push('/login');
      return;
    }
    //加载映射关系room,seat,dish,id->名映射
     this.loadMaputils()
    // 加载用户数据
    this.loadUserData();
    // 加载订单数据
    this.loadOrderData();
    // 加载收藏数据
    this.loadCollectionData();
     // 加载菜品分类
     this.loadDishCategories();
    
  },
  mounted(){
    this.fetchExistingOrders();
    this.fetchExistingOrdersSeat();
    
  },
  methods: {
    async loadMaputils() {
      try {
        const result=MapUtils.isEmpty()
          if(result.isRoomEmpty){
            await listRoom();
          }
          if(result.isSeatEmpty){
            await listSeat();
          }
          if(result.isDishEmpty){
            await listDish();
          }
        // if (response.code === 200) {
          
        // }
      } catch (error) {
        console.error('加载映射失败:', error);
      }
    },
     // 在表格渲染方法中使用
    formatRoomId(id) {
      return MapUtils.getRoomNumber(id);
    },
    formatSeatId(id) {
      return MapUtils.getSeatNumber(id);
    },
    formatDishId(id) {
      return MapUtils.getDishNumber(id);
    },
    async handlePayOrder(id,type){
      
      console.log("支付的类型为"+type);
      console.log("支付id为"+id);
        try {
          if (type === 'dish') {
            await updateDishorderStatusById(id);

          } else if(type === 'seat'){
            await updateSeatorderStatusById(id);
          }else if(type === 'room'){
             await updateRoomorderStatusById(id);
          }
            this.$message.success("支付成功");
            this.ItemShowDetailDialog = false;
            this.activeOrderTab = type;
            this.loadOrderData();
        } catch (error) {
           this.$message.error('支付失败');
            console.error(`支付处理失败`, error);
        }
    },
    async loadDishCategories() {
      try {
        const response = await listDishcategory();
        if (response.code === 200) {
          // 创建分类ID到名称的映射
          this.dishCategories = response.rows.reduce((map, category) => {
            map[category.id] = category.name;
            return map;
          }, {});
        }
      } catch (error) {
        console.error('加载菜品分类失败:', error);
      }
    },
    async fetchExistingOrders() {
      try {
        const response = await listRoomorder();
        if (response.code === 200) {
          // 只保留状态为1（待支付）和2（已支付）的订单
          this.existingOrders = response.rows.filter(
            order => order.status === 1 || order.status === 2
          );
        }
        
      } catch (error) {
        console.error('获取现有订单失败:', error);
        this.$message.error('获取房间预订信息失败，请稍后重试');
      }
    },
    async fetchExistingOrdersSeat() {
      try {
        const response = await listSeatorder();
        if (response.code === 200) {
          // 保留状态为“待支付”（1）和“已支付”（2）的有效订单
          this.existingSeats = response.rows.filter(
            order => order.status === 1 || order.status === 2
          );
        }
      } catch (error) {
        console.error('获取现有订单失败:', error);
        this.$message.error('获取房间预订信息失败，请稍后重试');
      }
    },
     // 预订房间
    async handleBookRoom() {
      if (!getToken()) {
        this.$message.warning('请先登录后再预订房间');
        this.$router.push('/login');
        return;
      }
      if (this.detailData.status !== 1) {
        this.$message.warning('该房间当前不可预订');
        return;
      }
      
      
      
      this.fetchExistingOrders();

       // 新增：日期冲突检测
      const checkInDate = new Date(this.roomReserveForm.checkInDate);
      const checkOutDate = new Date(this.roomReserveForm.checkOutDate);
      // 检查当前房间的已有预订 
      const hasConflict = this.existingOrders.some(order => {
        // 只检查相同房间的订单
        if (order.roomId !== this.detailData.id) return false;
        const existingCheckIn = new Date(order.checkInDate);
        const existingCheckOut = new Date(order.checkOutDate);
        // 检查日期是否重叠
        return (
          (checkInDate >= existingCheckIn && checkInDate < existingCheckOut) ||
          (checkOutDate > existingCheckIn && checkOutDate <= existingCheckOut) ||
          (checkInDate <= existingCheckIn && checkOutDate >= existingCheckOut) 
        );
      });
      //console.log("结果"+hasConflict);
      if (hasConflict) {
        this.$message.error('该房间在选定日期内已被预订，请选择其他日期');
        return;
      }
      
      
      this.roomBookingLoading = true;
      
      try {
        // 构建预订数据
        const orderData = {
          userId: getUserId(),
          roomId: this.detailData.id,
          checkInDate: this.roomReserveForm.checkInDate,
          checkOutDate: this.roomReserveForm.checkOutDate,
          paymentMethod: this.roomReserveForm.paymentMethod,
          totalPrice: this.totalPrice
        };
        
        // 调用预订API
        const response = await addRoomorder(orderData);
        
        if (response.code === 200) {
          this.$message.success('房间预订成功！');
          this.showDetailDialog = false;
        } else {
          this.$message.error(response.msg || '预订失败');
        }
      } catch (error) {
        console.error('房间预订失败:', error);
        this.$message.error(`预订失败: ${error.message || '请稍后重试'}`);
      } finally {
        this.roomBookingLoading = false;
        this.$refs.roomReserveForm.resetFields();
      }
    },
    
    // 计算房间价格
    calculateRoomPrice() {
      if (!this.detailData || !this.detailData.price) return 0;
      
      if (this.roomReserveForm.checkInDate && this.roomReserveForm.checkOutDate) {
        const start = new Date(this.roomReserveForm.checkInDate);
        const end = new Date(this.roomReserveForm.checkOutDate);
        const diffTime = Math.abs(end - start);
        const days = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        return days * this.detailData.price;
      }
      
      return this.detailData.price;
    },
    
    // 预订座位
    async handleBookSeat() {
      if (!getToken()) {
        this.$message.warning('请先登录后再预订座位');
        this.$router.push('/login');
        return;
      }
      
      // 表单验证
      if (!this.seatReserveForm.orderDate || !this.seatReserveForm.orderTime) {
        this.$message.warning('请选择预订日期和时间');
        return;
      }
      
      if (this.seatReserveForm.peopleCount < 1) {
        this.$message.warning('用餐人数至少为1人');
        return;
      }
        this.fetchExistingOrdersSeat();

      // 时间冲突检测
      const selectedDate = this.seatReserveForm.orderDate;
      const selectedTime = this.seatReserveForm.orderTime + ":00";  // 补全时间格式（如12:30→12:30:00）
      const seatId = this.detailData.id;
      
      const hasConflict = this.existingSeats.some(order => {
        // 同一座位、同一日期、时间间隔小于30分钟视为冲突
        return order.seatId === seatId && 
              order.orderDate === selectedDate && 
              Math.abs(new Date(`1970-01-01T${order.orderTime}`) - new Date(`1970-01-01T${selectedTime}`)) / (1000 * 60) < 30;
      });
      
      if (hasConflict) {
        this.$message.error('该座位在选定的日期和时间已被预订，请选择其他时间');
        return;
      }
      
      this.seatBookingLoading = true;
      
      try {
        const orderData = {
          userId: getUserId(),
          seatId: this.detailData.id,
          orderDate: this.seatReserveForm.orderDate,
          orderTime: this.seatReserveForm.orderTime+":00",
          peopleCount: this.seatReserveForm.peopleCount
        };
        
        const response = await addSeatorder(orderData);
        if (response.code === 200) {
          this.$message.success('座位预订成功');
          this.showDetailDialog = false;
        } else {
          this.$message.error(response.msg || '预订失败');
        }
      } catch (error) {
        console.error('座位预订失败:', error);
        this.$message.error(`预订失败: ${error.message || '请稍后重试'}`);
      } finally {
        this.seatBookingLoading = false;
      }
    },
    // 取消订单状态（将订单状态改为已取消）
    async handleCancelOrderStatus(type, orderId) {
      try {
        this.$confirm(`确定要取消该${type}订单吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let updateData = {};
          
          // 根据订单类型设置更新数据
          switch (type) {
            case 'room':
              // 在房间订单列表中找到该订单
              const roomOrder = this.roomOrders.find(order => order.id === orderId);
              if (roomOrder) {
                updateData = {
                  ...roomOrder,
                  status: 3 // 已取消状态
                };
                await updateRoomorder(updateData);
              }
              break;
              
            case 'seat':
              // 在座位订单列表中找到该订单
              const seatOrder = this.seatOrders.find(order => order.id === orderId);
              if (seatOrder) {
                updateData = {
                  ...seatOrder,
                  status: 3 // 已取消状态
                };
                await updateSeatorder(updateData);
              }
              break;
              
            case 'dish':
              // 在菜品订单列表中找到该订单
              const dishOrder = this.dishOrders.find(order => order.id === orderId);
              if (dishOrder) {
                updateData = {
                  ...dishOrder,
                  status: 3 // 已取消状态
                };
                await updateDishorder(updateData);
              }
              break;
          }
          
          this.$message.success('订单已取消');
          this.loadOrderData(); // 重新加载订单数据
        }).catch(() => {
          this.$message.info('已取消操作');
        });
      } catch (error) {
        console.error(`取消${type}订单失败:`, error);
        this.$message.error(`取消${type}订单失败: ${error.message || '请稍后重试'}`);
      }
    },
    
    // 加入购物车
    async handleAddToCart() {
      if (!getToken()) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      // 新增：验证菜品是否为上架状态（status=1）
      if (this.detailData.status !== 1) {
        this.$message.error('该菜品已下架，无法加入购物车');
        return;
      }
      this.cartLoading = true;
      
      try {
        const data = {
          userId: getUserId(),
          dishId: this.detailData.id,
          quantity: this.cartQuantity
        };
        
        const response = await addDishcart(data);
        if (response.code === 200) {
          this.$message.success(`已加入${this.cartQuantity}份到购物车`);
          this.showDetailDialog = false;
        } else {
          this.$message.error(response.msg || '加入购物车失败');
        }
      } catch (error) {
        console.error('加入购物车失败:', error);
        this.$message.error('加入购物车失败');
      } finally {
        this.cartLoading = false;
      }
    },
        // 显示项目详情（房间/座位）
    async showItemDetail(itemId, type,curId) {
      this.ItemDetailType = type;
      this.ItemShowDetailDialog = true;
      this.ItemDetailLoading = true;
      this.ItemDetailData = null;
      this.dishOrderDetail = null;
      this.dishOrderItems = [];
      this.ItemDishCategoryName = '';
      
      try {
        // 根据类型调用不同的API
        if (type === 'room') {
          this.currentRoomId=curId;
          const response = await getRoom(itemId);
          if (response.code === 200) {
            this.ItemDetailData = response.data;
            this.ItemDetailDialogTitle = '房间详情';
          }
        } 
        else if (type === 'seat') {
          this.currentSeatId=curId;
          const response = await getSeat(itemId);
          if (response.code === 200) {
            this.ItemDetailData = response.data;
            this.ItemDetailDialogTitle = '座位详情';
          }
        }else if(type === 'dish'){
          // 处理菜品订单详情
          const response = await getDishorder(itemId);
          if (response.code === 200) {
            this.dishOrderDetail = response.data;
            this.ItemDetailDialogTitle = `菜品订单详情 - 订单ID: ${this.dishOrderDetail.id}`;
            
            // 获取所有菜品详情
            const dishPromises = this.dishOrderDetail.dishorderitemList.map(async item => {
              const dishRes = await getDish(item.dishId);
              return {
                ...item,
                dishInfo: dishRes.code === 200 ? dishRes.data : null
              };
            });
            
            // 等待所有菜品详情加载完成
            this.dishOrderItems = await Promise.all(dishPromises);
          }
        }
      } catch (error) {
        console.error('获取详情失败:', error);
        this.$message.error('获取详情失败');
      } finally {
        this.ItemDetailLoading = false;
      }
    },
      // 显示收藏详情
    async showCollectionDetail(collection, type) {
      this.detailType = type;
      this.showDetailDialog = true;
      this.detailLoading = true;
      this.detailData = null;
      this.dishCategoryName = '';
      
      try {
        const itemId = collection.itemId;
        
        // 根据类型调用不同的API
        if (type === 'room') {
          const response = await getRoom(itemId);
          if (response.code === 200) {
            this.detailData = response.data;
            this.detailDialogTitle = '房间详情';
          }
        } 
        else if (type === 'seat') {
          const response = await getSeat(itemId);
          if (response.code === 200) {
            this.detailData = response.data;
            this.detailDialogTitle = '座位详情';
          }
        } 
        else if (type === 'dish') {
          const response = await getDish(itemId);
          if (response.code === 200) {
            this.detailData = response.data;
            this.detailDialogTitle = '菜品详情';
            
            // 获取菜品分类名称
            if (this.detailData.categoryId) {
              const categoryRes = await getDishcategory(this.detailData.categoryId);
              if (categoryRes.code === 200) {
                this.dishCategoryName = categoryRes.data.name;
              }
            }
          }
        }
      } catch (error) {
        console.error('获取收藏详情失败:', error);
        this.$message.error('获取收藏详情失败');
      } finally {
        this.detailLoading = false;
      }
    },
    // 加载用户信息
    async loadUserData() {
      try {
        const userId = getUserId();
        const response = await getUser(userId);
        if (response.code === 200) {
          this.userInfo = response.data;
          // 初始化编辑表单
          this.editForm = {
            username: response.data.username,
            phone: response.data.phone,
            email: response.data.email
          };
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.$message.error('获取用户信息失败');
      }
    },
    
    // 加载订单数据
    async loadOrderData() {
      const userId = getUserId();
      // 设置加载状态
      if (this.activeOrderTab === 'room') this.roomOrdersLoading = true;
      else if (this.activeOrderTab === 'seat') this.seatOrdersLoading = true;
      else if (this.activeOrderTab === 'dish') this.dishOrdersLoading = true;
      
      try {
        // 房间订单
        if (this.activeOrderTab === 'room' || !this.roomOrders.length) {
          const roomRes = await getRoomorderByUserId(userId);
          if (roomRes.code === 200) {
            this.roomOrders = roomRes.rows || [];
          }
          this.roomOrdersLoading = false;
        }
        
        // 座位订单
        if (this.activeOrderTab === 'seat' || !this.seatOrders.length) {
          const seatRes = await getSeatorderByUserId(userId);
          if (seatRes.code === 200) {
            this.seatOrders = seatRes.rows || [];
          }
          this.seatOrdersLoading = false;
        }
        
        // 菜品订单
        if (this.activeOrderTab === 'dish' || !this.dishOrders.length) {
          const dishRes = await getDishorderByUserId(userId);
          if (dishRes.code === 200) {
            this.dishOrders = dishRes.rows || [];
          }
          this.dishOrdersLoading = false;
        }
      } catch (error) {
        console.error('加载订单数据失败:', error);
        this.$message.error('加载订单数据失败');
        // 重置加载状态
        this.roomOrdersLoading = false;
        this.seatOrdersLoading = false;
        this.dishOrdersLoading = false;
      }
    },
    
    // 加载收藏数据
    async loadCollectionData() {
      this.collectionLoading = true;
      try {
        const userId = getUserId();
        const response = await getCollectionByUserId(userId);
        if (response.code === 200) {
          this.collections = response.rows || [];
        }
        this.collectionLoading = false;
      } catch (error) {
        console.error('加载收藏数据失败:', error);
        this.$message.error('加载收藏数据失败');
        this.collectionLoading = false;
      }
    },
    
    // 过滤收藏数据
    filterCollections(type) {
      return this.collections.filter(item => item.itemType === type);
    },
    
    // 获取订单状态标签类型
    getStatusType(status) {
      const map = {
        1: 'warning', // 待支付
        2: 'success', // 已支付
        3: 'info',    // 已取消
        4: ''         // 已完成
      };
      return map[status] || '';
    },
    
    // 获取订单状态文本
    getStatusText(status) {
      const map = {
        1: '待支付',
        2: '已支付',
        3: '已取消',
        4: '已完成'
      };
      return map[status] || '未知';
    },
    
    // 保存用户信息
    async saveUserInfo() {
      try {
        const userId = getUserId();
        const data = {
          id: userId,
          ...this.editForm
        };
        
        const response = await updateUser(data);
        if (response.code === 200) {
          this.$message.success('个人信息更新成功');
          this.showEditDialog = false;
          this.loadUserData(); // 刷新用户信息
        } else {
          this.$message.error(response.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新用户信息失败:', error);
        this.$message.error('更新用户信息失败');
      }
    },
    
    // 修改密码
    async changepassword() {
      this.$refs.passwordForm.validate(async valid => {
        if (!valid) return;
        
        try {
          const userId = getUserId();
          const data = {
            id: userId,
            oldPassword: this.passwordForm.oldPassword,
            password: this.passwordForm.newPassword
          };
          
          const response = await ChangePassword(data);
          if (response.code === 200) {
            this.$message.success('密码修改成功');
            this.showPasswordDialog = false;
            this.passwordForm = {
              oldPassword: '',
              newPassword: '',
              confirmPassword: ''
            };
          } else {
            this.$message.error(response.msg || '密码修改失败');
          }
        } catch (error) {
          console.error('修改密码失败:', error);
          this.$message.error('修改密码失败');
        }
      });
    },
    
    // 处理取消订单
    async handleCancelOrder(type, orderId) {
      try {
        this.$confirm(`确定要删除该${type}订单吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let result;
          switch (type) {
            case 'room':
              result = await delRoomorder(orderId);
              break;
            case 'seat':
              result = await delSeatorder(orderId);
              break;
            case 'dish':
              result = await delDishorder(orderId);
              break;
          }
          
          if (result && result.code === 200) {
            this.$message.success('订单取消成功');
            this.loadOrderData(); // 刷新订单数据
          } else {
            this.$message.error(result.msg || '取消失败');
          }
        }).catch(() => {
          this.$message.info('已取消操作');
        });
      } catch (error) {
        console.error('取消订单失败:', error);
        this.$message.error('取消订单失败');
      }
    },
    
    // 删除收藏
    async removeCollection(collection) {
      try {
        this.$confirm('确定要删除该收藏吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const data = {
            userId: collection.userId,
            itemType: collection.itemType,
            itemId: collection.itemId
          };
          
          const response = await delCollectionInfo(data);
          if (response.code === 200) {
            this.$message.success('收藏删除成功');
            this.loadCollectionData(); // 刷新收藏数据
          } else {
            this.$message.error(response.msg || '删除失败');
          }
        }).catch(() => {
          this.$message.info('已取消操作');
        });
      } catch (error) {
        console.error('删除收藏失败:', error);
        this.$message.error('删除收藏失败');
      }
    }
  }
};
</script>

<style scoped>
img {
  display: block;
  margin-top: 5px;
  border: 1px solid #ebeef5;
}
.user-center-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.page-header h1 {
  color: #303133;
  font-size: 24px;
  margin-bottom: 10px;
}

.page-header p {
  color: #909399;
  font-size: 14px;
}

.main-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-details {
  display: flex;
  padding: 10px 0;
}

.avatar-container {
  flex: 0 0 200px;
  text-align: center;
  padding: 10px;
  border-right: 1px solid #ebeef5;
}

.user-avatar {
  margin-bottom: 15px;
  border: 2px solid #409EFF;
}

.username {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.role {
  color: #67C23A;
  font-size: 14px;
}

.info-container {
  flex: 1;
  padding: 10px 20px;
}

.info-item {
  display: flex;
  margin-bottom: 15px;
  font-size: 14px;
}

.label {
  flex: 0 0 100px;
  color: #909399;
}

.value {
  flex: 1;
  color: #606266;
}

.status.active {
  color: #67C23A;
  font-weight: bold;
}

.order-tabs, .collection-tabs {
  margin-top: 30px;
}

.el-tabs__header {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 0 10px;
}

.el-tabs__item {
  font-weight: bold;
}

.el-tabs__content {
  padding: 15px 0;
}
</style>